package org.box.demos.multithreading.wgetmt;

import java.io.IOException;

import org.box.metadata.cli.CommandLineParser;
import org.box.metadata.cli.MetaCommandLineParser;
import org.box.metadata.cli.exception.ParseException;
import org.box.metadata.cli.util.HelpFormatter;

/**
 * The launcher for the application. It contains an entry point and Command Line
 * Interface for the user interacts with.
 * 
 * @author <a href="mailto:alexander.box@gmail.com">Alexander Korobka</a>
 * 
 */
public class Launcher {

	private final String[] args;

	/**
	 * The constructor
	 * 
	 * @param args
	 *            - a list of command line parameters
	 */
	public Launcher(String[] args) {
		this.args = args;
	}

	/**
	 * Start signal for App Launcher.
	 */
	public void start() {
		CommandLineParser<Configuration> parser = new MetaCommandLineParser<Configuration>(
				Configuration.class);

		try {
			Configuration cfg = parser.parse(args);

			// print the help section, if arg is '-h' or '--help'
			if (cfg.getUrls().size() == 0 ||  cfg.isHelp()) {
				printHelp();

			} else {
				
				WGetApp app = new WGetApp(cfg);
				app.run();
			}

		} catch (ParseException e) {
			System.out.println(e.getMessage());
			printHelp();
		} catch (IOException e) {
			throw new RuntimeException(e);
		}
	}

	/**
	 * Prints Usage section into output;
	 */
	private void printHelp() {

		HelpFormatter formatter = new HelpFormatter(Configuration.class);
		formatter.printHelp();

		System.exit(0);
	}

	/**
	 * The entry point of the app.
	 * 
	 * @param args
	 *            - a list of command line params
	 */
	public static void main(String[] args) {

		new Launcher(args).start();
	}

}
